Using arrays to hold information.
If we want to associate the name of the month with its number, we can use an array. The month in the first spot is January, while the twelfth spot holds December. Here is a bit of code that DIMs an array, then fills it with the names of the month so that the array index corresponds with the proper name. It then prints out the contents of the array.
dim month$(12)
month$(1)="January"
month$(2)="February"
month$(3)="March"
month$(4)="April"
month$(5)="May"
month$(6)="June"
month$(7)="July"
month$(8)="August"
month$(9)="September"
month$(10)="October"
month$(11)="November"
month$(12)="December"
for i = 1 to 12
print "Month ";i;" is named ";month$(i)
next
Filling arrays with READ and DATA
An alternate method of filling an array is to place the data in DATA statements. This can make for fewer lines of code and less typing, especially when there is a lot of data. We can READ the data and load it into the array. Here is some code that does that, and it uses fewer lines than the first example.
DATA "January","February","March","April","May","June","July"
DATA "August","September","October","November","December"
dim month$(12)
for i = 1 to 12
read mnth$
month$(i)=mnth$
print "Month ";i;" is named ";month$(i)
next
Using strings and word$()
We can avoid using arrays for this routine. We can place the names of the months into a string variable. The word$() function can then retrieve them, just as if they were in an array.
month$ = "January February March April May June July August "
month$ = month$ + "September October November December"
for i = 1 to 12
print "Month ";i;" is named ";word$(month$,i)
next
Usage in a program
Here is an example that uses this method to get input from the user and extract the name of the month when he selects a number.
month$ = "January February March April May June July August " month$ = month$ + "September October November December" print "Select a number from 1 to 12." input num$ num = val(num$) if num<1 then num=1 if num>12 then num=12 print "You selected month ";num;" which is named ";word$(month$,num)